package com.gxa.exchangerate.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Huilv {

    public static JSONArray run(){
        //java环境中文传值时，需特别注意字符编码问题
        String httpUrl = "http://api.tianapi.com/fxratelist/index?key=9d1fb3d6cf6451928d8978ab851a4a80&bank=icbc";
        String jsonResult = request(httpUrl);
        System.out.println(jsonResult);
        JSONObject jsonObject = JSON.parseObject(jsonResult);
//        System.out.println(jsonObject);
//        Integer code = (Integer) jsonObject.get("code");
//        System.out.println(code);
        JSONArray newslist = jsonObject.getJSONArray("newslist");
//        System.out.println(newslist);
        JSONObject list = newslist.getJSONObject(0);
//        System.out.println(list);
        JSONArray list1 = list.getJSONArray("list");
//        System.out.println(list1);
//        for (int i = 0; i < list1.size(); i++) {
//            JSONObject jsonObject1 = list1.getJSONObject(i);
//            String coin_name = jsonObject1.getString("coin_name");
//            System.out.println(coin_name);
//        }
        return list1;


    }



    public static String request(String httpUrl) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
//        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}